<template>
	<view>
		<u-swiper :circular="true" :list="banner" @change="e => currentNum = e.current" indicatorStyle="right: 20px"
			height="750rpx" imgMode="scaleToFill">
			<view slot="indicator" class="indicator-num">
				<text class="indicator-num__text">{{ currentNum + 1 }}/{{ banner.length }}</text>
			</view>
		</u-swiper>

		<view class="fixed nav" :style="{
			background:pageScroll >= 100 ? '#FFF' : 'transparent'
		}">
			<view class="" :style="{
				height:statusBarHeight+'px'
			}">

			</view>
			<view class="flex justify-around items-center back round mt-24" @click="handleBack">
				<image src="https://file.fulewanjia.com/fulewanjia/profile/appImg/index/icon_jiantou@2x.png" class="image-40"
					mode=""></image>
			</view>
		</view>

		<view class="px-20" v-if="detail">
			<view class="bg-FFF round-4 py-24 px-20 mt-24">
				<view class="flex items-center justify-between">
					<view class="text-32 font-700">
						{{detail.name}}
					</view>

					<!-- #ifdef MP-WEIXIN -->
					<view class="share-btn-wrap">
						<button open-type="share" class="share-btn"></button>
						<image src="https://file.fulewanjia.com/fulewanjia/profile/appImages/common/share.png"
							style="width: 40rpx;" mode="widthFix"></image>
					</view>
					<!-- #endif -->
				</view>


				<!-- 	<view class="text-28 mt-20 text-8EAC31" v-if="detail.sendGreenIntegralNum">
					赠送绿色积分:{{detail.sendGreenIntegralNum}}
				</view> -->

				<view class="flex items-center justify-between mt-20">
					<view class="flex items-center">
						<view class="sprice text-40">
							{{ detail.nowPrice }}{{detail.columnType == 6 ? '可兑换熵豆' : '元'}}
							<text style="color: #41B721;"
								v-if="detail.xiaofeijinPrice">+{{ detail.xiaofeijinPrice}}元熵豆</text>
						</view>
					</view>
					<view class="" v-if="detail.columnType != 13">
						{{detail.salesNum || 0}}人付款
					</view>
				</view>

				<view class="sprice mt-12" v-if="detail.columnType != 6 && detail.shangdou">
					赠送{{detail.shangdou}}元熵豆
				</view>
			</view>

			<!-- <view class="bg-FFF round-4 py-12 px-20 mt-24 flex items-center justify-between">
				<view class="flex items-center">
					<image src="https://file.fulewanjia.com/fulewanjia/profile/appImg/index/icon_zhenpinbaozhang@2x.png"
						class="image-40" mode=""></image>
					<view class="text-28 ml-12 text-gray">
						正品保证
					</view>
				</view>
				<view class="flex items-center">
					<image src="https://file.fulewanjia.com/fulewanjia/profile/appImg/index/icon_jiayipeishi@2x.png"
						class="image-40" mode=""></image>
					<view class="text-28 ml-12 text-gray">
						假一赔十
					</view>
				</view>
				<view class="flex items-center">
					<image src="https://file.fulewanjia.com/fulewanjia/profile/appImg/index/icon_baoyou@2x.png" class="image-40"
						mode=""></image>
					<view class="text-28 ml-12 text-gray">
						快递包邮
					</view>
				</view>
				<view class="flex items-center">
					<image src="https://file.fulewanjia.com/fulewanjia/profile/appImg/index/icon_tuijian@2x.png"
						class="image-40" mode=""></image>
					<view class="text-28 ml-12 text-gray">
						好物推荐
					</view>
				</view>
			</view> -->

			<view class="bg-FFF round-4 py-12 px-20 mt-24" v-if="detail.columnType == 3">
				<view class="flex justify-between">
					<view class="flex align-center">
						<view class="box-1">
						</view>
						<view class="text-36 font-700 ml-12">
							店铺推荐
						</view>
					</view>
					<view class="flex items-center" @click="goShop">
						<text class="text-28 mr-12 box-2">进入店铺</text>
						<u-icon name="arrow-right" color="#E2382B" size="14" bold></u-icon>
					</view>
				</view>
				<view class="mt-24">
					<scroll-view scroll-x="true">
						<view class="flex items-center round-12 ">
							<view class="productBox mr-24 p-20" v-for="(item, index) in commodityList" :key="index">
								<view class="flex justify-around">
									<image :src="item.icon" class="productImg round-4" mode=""></image>
								</view>
								<view class="text-28 u-line-1 mt-12">
									{{item.name}}
								</view>
								<view class="sprice">
									￥{{item.nowPrice}}
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>

			<view class="bg-FFF round-4 py-12 px-20 mt-24" >
				<view class="flex justify-between">
					<view class="flex align-center">
						<view class="box-1">
						</view>
						<view class="text-36 font-700 ml-12">
							用户评价({{reply.sumCount || 0}})
						</view>
					</view>
					<view class="flex items-center" @click="goReply">
						<text class="text-28 mr-12 box-2">好评</text>
						<text class="text-28 mr-12 box-2">{{reply.replyChance ? reply.replyChance * 100 : 0}}% </text>
						<u-icon name="arrow-right" color="#E2382B" size="14" bold></u-icon>
					</view>
				</view>
			</view>
			<view class="bg-FFF round-4 py-12 px-20 mt-24">
				<view class="flex align-center">
					<view class="box-1 ">
					</view>
					<view class="text-36 ml-12 font-700">
						商品详情
					</view>
				</view>

				<view class="my-20">
					<mp-html :content="detail.detail" style="font-size: 0;" />
				</view>
			</view>
		</view>

		<view class="" style="height: 300rpx;">

		</view>


		<view class="footer iphoneX" v-if="detail">
			<view class="px-20 py-20 flex align-center justify-between" style="padding-bottom: 50rpx;">
				<view class="flex align-center justify-around" style="width: 290rpx;">
					<view class="flex align-center flex-col" @click="phoneShop"
						v-if="storeId != 'null' && detail.columnType != 12">
						<image
							src="https://file.fulewanjia.com/fulewanjia/profile/appImages5/icon_dianpu@2x.png"
							class="image-40" mode=""></image>
						<view class="text-24 ">
							店铺
						</view>
					</view>
					
					<view class="flex align-center flex-col ml-12" @click="handleChat"
						v-if="detail.mallZoneUser">
						<image
							src="https://file.fulewanjia.com/fulewanjia/profile/chatImgs/icon_liaotiankefu@3x.png"
							class="image-40" mode=""></image>
						<view class="text-24">
							在线客服
						</view>
					</view>

					<view class="flex align-center flex-col ml-12" @click="collectClick" v-if="detail.columnType != 12">
						<image v-if="detail.isCollect!=1"
							src="https://file.fulewanjia.com/fulewanjia/profile/preImages/home/icon_shoucang.png"
							class="image-40" mode="" />
						<image v-if="detail.isCollect==1"
							src="https://file.fulewanjia.com/fulewanjia/profile/preImages/home/icon_shoucang_xuanzhong.png"
							class="image-40" mode="" />
						<view class="text-24">
							收藏
						</view>
					</view>
				</view>
				<view class="flex align-center">
					<view class="buyBtn text-center text-28 text-FFF" @click="buyConfirm(2)">
						立即购买
					</view>
				</view>
			</view>
		</view>

		<!-- 购物弹出 -->
		<u-popup :show="isSpecShow" @close="isSpecShow=false" mode="bottom">
			<view class="px-20 py-32">
				<view class="px-20">
					<view class="flex relative">
						<image :src="skuData.icon" class="round-12 specImg" mode="">
						</image>
						<view class="ml-24 text-left">
							<view class="flex items-center">
								<view class="text-32 sprice">
									￥{{skuData.nowPrice}}
								</view>
								<view class="text-24 ml-24 old-price">
									原价:{{skuData.price}}
								</view>
							</view>
							<view class="text-24 text-grey1 mt-16">
								存库：{{skuData.stock}}
							</view>
							<view class="mt-16" v-if="pageSkuList.length >= 1">
								{{pageSkuList[0].skuName}}:{{pageSkuList[0].specList[pageSkuList[0].selectIndex]}}
							</view>
							<view class="" v-if="pageSkuList.length == 2">
								{{pageSkuList[1].skuName}}:{{pageSkuList[1].specList[pageSkuList[1].selectIndex]}}
							</view>
						</view>
					</view>
					<!-- S 规格 -->
					<scroll-view scroll-y="true">
						<view class="mt-40">
							<view v-for="(item,index) in pageSkuList" :key="index">
								<view class="my-28">
									{{item.skuName}}
								</view>
								<view class="flex flex-wrap">
									<view @click="changeSkuIndex(item,j)" v-for="(i,j) in item.specList" :key="j"
										class="round-8 px-20 py-12 mr-20 mb-20"
										:style="{background:`${item.selectIndex == j ?'#F88319' :'#EBEBEB' }`,color:`${item.selectIndex == j ? '#fff' :'#BCBCBC ' }`}">
										{{i}}
									</view>
								</view>
							</view>
						</view>
						<view class="mt-28 flex align-center justify-between mb-20">
							<view class="text-32 font-700">
								请选择数量
							</view>
							<u-number-box v-model="skuData.num"></u-number-box>
						</view>
					</scroll-view>
					<!-- E 规格 -->
					<view class="flex justify-around align-center px-20 py-20 pb-48 mt-48">
						<view class="joinCar text-28 text-center"
							:style="{background:`${skuData.stock>0 ?'#1A1A1A' :'#eee' }`,color:`${skuData.stock>0?'#fff' :'#999' }`}"
							@click="joinCar" style="width: 256rpx;" v-if="detail && detail.columnType == 3">
							加入购物车
						</view>
						
						<view class="buyBtn text-28 text-center"
							:style="{background:`${skuData.stock>0 ?'linear-gradient( 180deg, #FF561D 33%, #FF0064 100%)' :'#eee' }`,color:`${skuData.stock>0?'#fff' :'#999' }`}"
							@click="createOrder" style="width: 256rpx;">
							立即支付
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		
		<image src="https://file.fulewanjia.com/fulewanjia/profile/appImages5/icon_gouwuche 2@2x.png" class="cart-img" mode="" @click="$tab.nav(`/pages/shoppingCart?storeId=${storeId}`)" v-if="detail && detail.columnType == 3 && storeId"></image>
	</view>
</template>

<script>
	import {
		getToken
	} from "@/utils/auth"
	import {
		throttle
	} from 'throttle-debounce';
	var thro;
	export default {
		data() {
			return {
				storeId: "",
				productId: "",
				detail: null,
				reply:{
					goodCount: 0,
					inCount: 0,
					poorCount:0,
					replyChance: "0",
					replyStar: 0,
					sumCount: 0
				},
				banner: [],
				currentNum: 0,
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				pageScroll: 0,
				commodityList: [],
				storeDetail: null,
				value: 1,
				globalConfig: getApp().globalData.config,

				isSpecShow: false, //商品规则弹窗
				skuData: {
					id: null, //创建订单时的skuid
					icon: null, //页面显示的图片
					stock: null, //库存
					price: null, //价格
					xiaofeijinPrice: null, //可使用消费金
					num: 1, //购买的数量
				}, //商品规格显示数据
				pageSkuList: [], //页面上要显示的
				skuList: null, // 后台返回的
				isShare: false
			};
		},
		watch: {
			pageSkuList: {
				handler(newVal) {
					this.skuList.forEach(item => {
						if (newVal.length == 1) {
							if (item.mallSkuSpecs[0].specValue == newVal[0].specList[newVal[0].selectIndex]) {
								this.skuData.id = item.id
								this.skuData.icon = this.globalConfig.imagePrefix + item.icons
								this.skuData.stock = item.stock
								this.skuData.price = item.price
								this.skuData.nowPrice = item.nowPrice || null
							}
						} else if (newVal.length == 2) {
							if ((item.mallSkuSpecs[0].specValue == newVal[0].specList[newVal[0].selectIndex] &&
									item
									.mallSkuSpecs[1].specValue == newVal[1].specList[newVal[1].selectIndex]) || (
									item
									.mallSkuSpecs[1].specValue == newVal[0].specList[newVal[0].selectIndex] && item
									.mallSkuSpecs[0].specValue == newVal[1].specList[newVal[1].selectIndex])) {
								this.skuData.id = item.id
								this.skuData.icon = this.globalConfig.imagePrefix + item.icons
								this.skuData.stock = item.stock
								this.skuData.price = item.price
								this.skuData.nowPrice = item.nowPrice || null
							}
						}
					})
				},
				deep: true
			}
		},
		onLoad(e) {
			thro = this
			// #ifdef MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
			// #endif

			if (uni.getStorageSync('commodity')) {
				e = uni.getStorageSync('commodity')
				uni.removeStorageSync('commodity')
			}

			if (e && e.inviteCode) {
				this.isShare = true
				if (getToken()) {
					this.$Api.user.bindSuperiorByInviteCode(e.inviteCode)
				} else {
					uni.setStorageSync('commodity', {
						storeId: e.storeId,
						id: e.id,
						inviteCode: e.inviteCode
					})
					uni.reLaunch({
						url: '/pages/login'
					})
				}
			} else {
				this.isShare = false
			}

			this.storeId = e.storeId
			this.productId = e.id
			this.getData()
		},
		onShareAppMessage(res) {
			let pages = getCurrentPages(); //获取当前页面栈的信息
			let currentPage = pages[pages.length - 1]; //获取到当前页面栈中最后一个页面的索引
			return {
				title: this.detail.name,
				path: currentPage.route +
					`?id=${this.productId}&storeId=${this.storeId}&inviteCode=${this.$store.getters.userInfo.inviteCode}` //后面是路径上要传递的参数
			}
		},
		onPageScroll(e) {
			this.pageScroll = e.scrollTop
		},
		methods: {
			async handleChat(){
				const res = await this.$Api.chat.mallService({
					userId:this.detail.mallZoneUser.userId
				})
				
				this.$tab.nav(`/pages/chat2/chatIndex?groupId=${res.groupId}&title=${res.title}&isGroup=0&id=${res.id}`)
			},
			handleBack() {
				if (this.isShare) {
					uni.switchTab({
						url: "/pages/indexPage"
					})
				} else {
					this.$tab.back()
				}
			},
			changeSkuIndex(item, index) {
				item.selectIndex = index
			},
			buyConfirm: throttle(2000, (e) => {
				if (thro.skuList == null) {
					if (e == 1) {
						thro.joinCar()
					} else {
						thro.createOrder()
					}
				} else {
					thro.isSpecShow = true
				}
			},{
				noTrailing:true
			}),
			async joinCar() {
				let params = {};
				params.spuId = this.productId
				if (this.skuList == null) {
					params.num = 1
				} else {
					if (this.skuData.stock < 0) {
						this.$modal.msg('该规格暂无库存')
						return
					}
					if (this.skuData.num > this.skuData.stock) {
						this.$modal.msg('购买量大于库存量')
						return
					}
					params.skuId = this.skuData.id
					params.num = this.skuData.num
				}

				if (this.storeId != 'null') {
					params.storeId = this.storeId
				}
				params.columnType = this.detail.columnType

				const res = await this.$Api.index.addCart(params)
				console.log('加入购物车', res)
				this.$modal.msg('添加成功!')
				this.isSpecShow = false
			},
			createOrder: throttle(2000, async () => {
				let params = {};
				params.spuId = thro.productId
				if (thro.skuList == null) {
					params.num = 1
				} else {
					if (thro.skuData.stock < 0) {
						thro.$modal.msg('该规格暂无库存')
						return
					}
					if (thro.skuData.num > thro.skuData.stock) {
						thro.$modal.msg('购买量大于库存量')
						return
					}
					params.skuId = thro.skuData.id
					params.num = thro.skuData.num
				}

				if (thro.storeId != 'null') {
					params.storeId = thro.storeId
				}

				const res = await thro.$Api.index.addOrder({
					orderSpuList: [{
						...params
					}]
				})
				console.log('创建订单', res)

				thro.$tab.nav(`/pages/mine/order/orderDetail?id=${res.msg}`)
			},{
				noTrailing:true
			}),
			goShop() {
				this.$tab.nav(`/pages/shops/detail?id=${this.storeId}`)
			},
			goReply() {
				this.$tab.nav(`/pages/commodity/reply?id=${this.productId}`)
			},
			goCar() {
				this.$tab.nav(`/pages/shoppingCart`)
			},
			async getData(e) {
				const detail = await this.$Api.index.commodityDetail(this.productId)
				const reply = await this.$Api.index.replyConfig(this.productId)
				console.log("🚀🚀🚀 ~ getData ~ replyNum:", reply)
				// const detail = await this.$Api.index.commodityDetail(this.productId)
				console.log('商品详情', detail)

				this.detail = detail.data
				this.reply = reply.data
				this.banner = detail.data.icons.split(',')
				this.banner = this.banner.map(item => {
					return this.globalConfig.imagePrefix + item
				})
				if (!e) {
					if (this.storeId && this.storeId != 'null') {
						const commodity = await this.$Api.index.getProductsList({
							pageNum: 1,
							pageSize: 10,
							storeId: this.storeId
						})

						this.commodityList = commodity.rows.map(item => {
							item.icon = this.globalConfig.imagePrefix + item.cover
							return item
						})

						const storeDetail = await this.$Api.index.getStoreInfo(this.storeId)

						this.storeDetail = storeDetail.data
					}
				}

				// 处理规格数据
				if (detail.data.mallSkus.length > 0) {
					this.skuList = detail.data.mallSkus
					// 根据mallSkuSpecs 得到 页面的初始 商品属性名
					this.pageSkuList = []
					this.skuList[0].mallSkuSpecs.forEach(item => {
						this.pageSkuList.push({
							skuName: item.specName,
							selectIndex: 0,
							specList: []
						})
					})

					// 循环渲染得到 完整的商品规格
					this.skuList.forEach(item => {
						item.mallSkuSpecs.forEach(i => {
							this.pageSkuList.forEach((l, index) => {
								if (i.specName == l.skuName) {
									const findIndex = this.pageSkuList[index].specList
										.findIndex(sname => {
											return sname === i.specValue
										})

									if (findIndex == -1) {
										this.pageSkuList[index].specList.push(i.specValue)
									}
								}
							})
						})
					})
				}
			},
			phoneShop() {
				uni.makePhoneCall({
					phoneNumber: this.storeDetail.linkerMobile //仅为示例
				});
			},
			collectClick() {
				if (this.detail.isCollect == 1) {
					this.$Api.index.cancelCollection({
						colType: 2,
						relateId: this.productId
					}).then(res => {
						this.getData(true)
					})
				} else {
					this.$Api.index.addCollection({
						colType: 2,
						relateId: this.productId
					}).then(res => {
						this.getData(true)
						uni.$u.toast('收藏成功');
					})
				}
			}
		}
	}
</script>

<style>
	page {
		background-color: #F8F8F8;
	}
</style>

<style lang="scss">
	.indicator-num {
		padding: 4rpx 0;
		background-color: rgba(0, 0, 0, 0.35);
		border-radius: 200rpx;
		width: 70rpx;
		@include flex;
		justify-content: center;

		&__text {
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}

	.nav {
		width: 100%;
		left: 0;
		top: 0;
		box-shadow: none !important;

		.back {
			width: 50rpx;
			height: 50rpx;
			position: absolute;
			left: 24rpx;
			top: 84rpx;
			background-color: rgba(0, 0, 0, 0.55);
		}
	}
	
	.cart-img{
		width: 112rpx;
		height: 112rpx;
		position: fixed;
		right: 20rpx;
		bottom: 160rpx;
	}

	.box-1 {
		width: 1rpx;
		height: 20rpx;
		background-color: #E2382B;
	}

	.box-2 {
		color: #E2382B;
		padding-bottom: 4rpx;
	}

	.productImg {
		width: 220rpx;
		height: 220rpx;
	}

	.share-btn-wrap {
		width: 40rpx;
		height: 40rpx;
		position: relative;

		.share-btn {
			width: 40rpx;
			height: 40rpx;
			border: none;
			border-color: transparent;
			background: none !important;
			position: absolute;
			left: 0;
			top: 0;
			z-index: 1;

			&:after {
				border: none;
				background: none !important;
			}
		}
	}

	.productBox {
		box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(153, 153, 153, 0.16);
		border: 2rpx solid #F1F1F1;
	}

	.footer {
		width: 100%;
		background: #FFFFFF;
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 999;
	}

	.joinCar {
		width: 216rpx;
		height: 68rpx;
		background: linear-gradient(90deg, #FFAE01 0%, #FF8C01 100%);
		border-radius: 376rpx 376rpx 376rpx 376rpx;
		line-height: 68rpx;
	}

	.buyBtn {
		width: 452rpx;
		line-height: 68rpx;
		background: linear-gradient(180deg, #FF561D 33%, #FF0064 100%);
		height: 68rpx;
		border-radius: 376rpx 376rpx 376rpx 376rpx;
	}

	.specImg {
		width: 200rpx;
		height: 200rpx;
	}
</style>